package customerEnter.Frame.JDBCDao.daoFrame;

import java.lang.reflect.Method;
import java.util.List;

import customerEnter.Frame.Annotation.FrameRedisCache;
import customerEnter.Frame.DaoDataTransmission.DaoFrameDMLBaseTransmission;
import customerEnter.Frame.DaoDataTransmission.DaoFramePameTransmission;
import customerEnter.Frame.Error.FramErrorProcessing;
import customerEnter.Frame.JDBCDao.Interface.DaoFrameIntermediateLayerInterface;
import customerEnter.Frame.JDBCDao.Interface.DaoFrameSqlProcessingInterface;
import customerEnter.Frame.JDBCDao.Interface.SqlExistenceResult;
import customerEnter.Frame.JDBCDao.JdbcTemplate.DynamicDataSourceHolder;
import customerEnter.Frame.JDBCDao.Proxy.FrameInvocationHandler;
import customerEnter.Frame.JDBCDao.util.DaoFrameConntroller;
import customerEnter.Frame.Thread.StackTraceElements;
import customerEnter.Frame.Thread.impl.FrameStackTraceElementImpl;
import customerEnter.Frame.Thread.interfaces.FrameStackTraceElement;
import customerEnter.Frame.Utils.Log4j;
import customerEnter.Frame.daoTransaction.IcyDataTemplateFactory;
import customerEnter.tool.springBeans;

/**
 * 數據查詢的基類 框架的一層助手類
 * 
 * 类名称：DaoFrameTransmission 类描述： 创建人：dy 创建时间：2016-3-28 上午8:56:38
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class DaoFrameMiddleware<T, K> extends DaoFramMiddlAssistant<T, K> implements
		DaoFrameIntermediateLayerInterface<T, K> {

	FrameInvocationHandler	frameInvocationHandler	= springBeans.getBean("frameInvocationHandler");

	IcyDataTemplateFactory	icyDataTemplateFactory	= springBeans.getBean("icyDataTemplateFactory");

	// 失敗的讀寫分離
	// FrameReadWriteInit frameReadWriteInit =
	// springBeans.getBean("frameReadWriteInit");

	/**
	 * 判斷執行成不成功 true 成功 false 不成功
	 */
	// private Boolean WhileQuerySql(String type, DaoFramePameTransmission<T, K>
	// daoFramePameTransmission) {
	// Boolean boolean1 = true;
	// if (type.equals("PreparedStatement"))
	// /**
	// * 執行語句
	// */
	// Log4j.Log4jOutInfo(daoFramePameTransmission.SQL);
	// try {
	// daoFramePameTransmission.sqlRowSet =
	// EasyBuyDB.getJdbcTemplate().queryForRowSet(
	// daoFramePameTransmission.SQL);
	// } catch (Exception e) {
	// String mString = "";
	// if (RandomDataSource.DataSourceController == 0) {
	// RandomDataSource.setDataSourceController(DataSourceControllerEnum.Controller_DataSource_1);
	// boolean1 = true;// 等於false 再次執行本方法
	// mString = "切換數據源" + RandomDataSource.DataSourceController;
	// } else if (RandomDataSource.DataSourceController == 1) {
	// boolean1 = true;// 等於true 繼續往下執行
	// mString = " 語法錯誤";
	// }
	// Log4j.Log4jOutInfo("執行失敗 ：" + e.getMessage() + "_______" + mString);
	// }
	// return boolean1;
	// }
	/**
	 * 功能： 判斷緩存有沒有 緩存存活3分鐘 用json sql語句為key 保證同一條sql語句 3分鐘內只訪問一次數據庫 包括沒緩存的時候查詢數據庫
	 * 
	 * @throws FramErrorProcessing
	 */
	public DaoFramePameTransmission<T, K> DMLTransmission(DaoFrameDMLBaseTransmission daoFrameDMLBaseTransmission,
			DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		// DataSourceExistence();

		// 解析sql語句
		SqlProcessing(
				DaoFrameConntroller.getDaoFrameSqlProcessingInterface(daoFramePameTransmission.getFrameDataSqlDMLUse()),
				daoFrameDMLBaseTransmission, daoFramePameTransmission);
		// 運行讀寫分離機制 失敗的讀寫分離
		// stackRunDataSource(DaoFrameConntroller.iniTraceElement());

		Log4j.Log4jOutInfo(daoFramePameTransmission.frameDataSqlDMLUse + ":"
				+ daoFrameDMLBaseTransmission.getClassName() + ":" + daoFramePameTransmission.SQL);
		Log4j.Log4jOutInfo("conn URL---->" + DynamicDataSourceHolder.getDataSource());
		// 執行sql和 處理結果集

		SqlExistenceResult(
				DaoFrameConntroller.sqlExistenceResultInterface(daoFramePameTransmission.getFrameDataSqlDMLUse()),
				daoFrameDMLBaseTransmission, daoFramePameTransmission);

		// if (daoFrameDMLBaseTransmission.isIfEhcache()) {
		// IfCache(daoFrameDMLBaseTransmission, daoFramePameTransmission);
		// } else {
		// setFindConditionQueryTo(daoFramePameTransmission);
		// }
		// daoFramePameTransmission.getPagingParametersResult();

		return daoFramePameTransmission;
	}

	void SqlProcessing(DaoFrameSqlProcessingInterface daoFrameSqlProcessingInterface,
			DaoFrameDMLBaseTransmission daoFrameDMLBaseTransmission,
			DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		daoFrameSqlProcessingInterface.SqlProcessing(daoFrameDMLBaseTransmission, daoFramePameTransmission);
	}

	void SqlExistenceResult(SqlExistenceResult sqlExistenceResult,
			DaoFrameDMLBaseTransmission daoFrameDMLBaseTransmission,
			DaoFramePameTransmission<T, K> daoFramePameTransmission) {
		daoFramePameTransmission.setReturnId(daoFrameDMLBaseTransmission.isReturnId());
		// 判斷緩存註解
		ifCaches(daoFramePameTransmission, daoFrameDMLBaseTransmission);
		// 查找緩存
		if (daoFrameDMLBaseTransmission.isIfEhcache()) {
			try {
				// 判斷緩存中 有沒有數據
				if (!ifCache(daoFramePameTransmission)) {
					sqlExistenceResult.execuesResult(daoFramePameTransmission, frameInvocationHandler,
							icyDataTemplateFactory);
					SetEachAddParameter(daoFramePameTransmission);
				} else {
					queryCache(daoFrameDMLBaseTransmission, daoFramePameTransmission);
				}
			} catch (Exception e) {
				Log4j.Log4jOutInfo("--缓存系统服务執行失敗--查询数据库--" + e.getMessage());
			}
		} else {
			sqlExistenceResult.execuesResult(daoFramePameTransmission, frameInvocationHandler, icyDataTemplateFactory);
		}
	}

	public void ifCaches(DaoFramePameTransmission<T, K> daoFramePameTransmission,
			DaoFrameDMLBaseTransmission daoFrameDMLBaseTransmission) {
		if (!daoFrameDMLBaseTransmission.isIfEhcache()) {
			daoFrameDMLBaseTransmission.setIfEhcache(false);
			FrameStackTraceElement frameStackTraceElement = new FrameStackTraceElementImpl();
			List<StackTraceElements> list = frameStackTraceElement.getStackTraceElements();
			for (StackTraceElements stackTraceElements : list) {
				String className = stackTraceElements.getClassName();
				String methodName = stackTraceElements.getMethodName();
				String key = className + "_" + methodName;
				if (!DaoFrameConntroller.IsRedisCacheAnnotationKey(key)) {
					try {
						Class<?> class1 = Class.forName(className);
						Method[] m = class1.getDeclaredMethods();
						for (Method method : m) {
							String key2 = className + "_" + method.getName();
							DaoFrameConntroller.PutRedisCacheAnnotation(key2,
									method.getAnnotation(FrameRedisCache.class));
						}
					} catch (ClassNotFoundException e) {
						System.out.println("獲取類失敗");
					}
				}
				if (DaoFrameConntroller.IsRedisCacheAnnotationKey(key)) {
					FrameRedisCache frameRedisCache = DaoFrameConntroller.getRedisCacheAnnotation(key);
					if (frameRedisCache != null) {
						daoFramePameTransmission.timeUnit = frameRedisCache.timeUnit();
						daoFramePameTransmission.CacheTime = frameRedisCache.time();
						daoFrameDMLBaseTransmission.setIfEhcache(true);
						break;
					}
				}
			}
		}
	}
	// 失敗的讀寫分離
	// private void stackRunDataSource(FrameStackTraceElement stackTraceElement)
	// {
	// if (WhetherToEmpty.ObjectWhetherToEmpty(frameReadWriteInit)) {
	// Log4j.Log4jOutInfo("frameReadWriteInit is null");
	// } else {
	// frameReadWriteInit.InitDataSourceRW(stackTraceElement.getStackTraceElements());
	// }
	// }
	/**
	 * 跳轉到 查詢數據庫 並且設置緩存方法
	 */
	// private void setFindConditionQueryTo(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission) {
	// Log4j.Log4jOutInfo("-----------------------------------查询数据库-----------------------");
	// try {
	// userQueryType(daoFramePameTransmission);
	// } catch (FramErrorProcessing e) {
	// Log4j.setLog4j(getClass());
	// Log4j.Log4jOutInfo(e.getMessage());
	// }
	// if (!daoFramePameTransmission.isIfUpdate()) {
	// SetEachAddParameter(daoFramePameTransmission);
	// }
	// }

	/**
	 * 增加方法
	 */
	// public void setInsertSql(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission, String DataBase,
	// String TableName, LinkedList<?> values) {
	// StringBuffer cen = new StringBuffer();
	// WhileLinkedList(values, cen);
	// daoFramePameTransmission.SQL = DaoFrameConntroller.SqlManage(DataBase,
	// " insert ", "", "into", TableName,
	// "values(" + cen + " ) ");
	// }

	/**
	 * 增加數據的方法
	 * 
	 * @throws ReflectiveOperationException
	 * @throws IllegalArgumentException
	 */
	// public void setInsertMappingSql(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission, String DataBase,
	// String TableName, Object t) throws Exception {
	// DaoFramUpdateOrAddMap daoFramUpdateOrAddMap =
	// javaReflexClass.getObjectNamesAndValuesAdd(t);
	// String fieldNames = "";
	// String values = "";
	// for (Entry<String, Object> entry :
	// daoFramUpdateOrAddMap.getData().entrySet()) {
	// if (!WhetherToEmpty.StringWhetherToEmpty(fieldNames)) {
	// fieldNames += ",";
	// values += ",";
	// }
	// fieldNames += entry.getKey();
	// values += entry.getValue();
	// }
	// daoFramePameTransmission.SQL = DaoFrameConntroller.SqlManage(DataBase,
	// " insert ", "", "into", TableName + "("
	// + fieldNames + ")", "values(" + values + " ) ");
	// }

	/**
	 * 修改數據的方法
	 * 
	 * @throws ReflectiveOperationException
	 * @throws IllegalArgumentException
	 */
	// public void setUpdateMappingSql(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission, String DataBase,
	// String TableName, Object t, String where) throws Exception {
	// String string = "";// 獲取全部屬性的類
	// DaoFramUpdateOrAddMap daoFramUpdateOrAddMap =
	// javaReflexClass.getObjectNamesAndValuesUpdate(t);
	// for (Entry<String, Object> entry :
	// daoFramUpdateOrAddMap.getData().entrySet()) {
	// if (!WhetherToEmpty.StringWhetherToEmpty(string)) {
	// string += ",";
	// }
	// string += entry.getKey() + "=" + entry.getValue();
	// }
	// daoFramePameTransmission.SQL = DaoFrameConntroller.SqlManage(DataBase,
	// " update ", TableName, " set ", string,
	// " where 1=1  " + where);
	// }

	// public String IfSqlError(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission) {
	// Integer integer = 0;
	// String error = ":null";
	// try {
	// integer = setInsertExec(daoFramePameTransmission);
	// } catch (Exception e) {
	// Log4j.Log4JOutError(e.getMessage());
	// integer = 0;
	// error = e.getMessage();
	// }
	// return integer > 0 ? "success:" + integer + " 条數據執行成功" : "fiel" + error;
	// }

	// public SqlRowSet setResultQuery(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission) {
	// Boolean boolean1 = false;
	// while (!boolean1) {
	// boolean1 = WhileQuerySql(daoFramePameTransmission.SqltatementType,
	// daoFramePameTransmission);
	// }
	// return daoFramePameTransmission.sqlRowSet;
	// }

	/**
	 * 封裝rs
	 * 
	 * @param <Y>
	 * @throws FramErrorProcessing
	 */

	// public <Y> void userQueryType(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission) throws FramErrorProcessing {
	// FrameInvocationHandler frameInvocationHandler =
	// springBeans.getBean("frameInvocationHandler");
	// DaoFrameUseTypeInterface daoFrameUseTypeInterface =
	// (DaoFrameUseTypeInterface) frameInvocationHandler
	// .invokeProxyObject(getDaoFrameUseTypeInterface(daoFramePameTransmission.getFrameDataSqlDMLUse()),
	// daoFramePameTransmission);
	// Y y = (Y)
	// daoFrameUseTypeInterface.useDaoFrameDataType(daoFramePameTransmission);
	// daoFramePameTransmission.getPagingParametersResult().setpObject(y);
	// }

	// public <Y> void userQueryType(DaoFramePameTransmission<T, K>
	// daoFramePameTransmission) throws FramErrorProcessing {
	// 靜態代理
	// UseQueryProxyJDBC useQueryProxyJDBC = new
	// UseQueryProxy(getDaoFrameUseTypeInterface(daoFramePameTransmission),
	// daoFramePameTransmission);
	// useQueryProxyJDBC.OpenConnection();
	// Y y = (Y)
	// useQueryProxyJDBC.useDaoFrameDataType(daoFramePameTransmission);
	// useQueryProxyJDBC.closeConnection();
	// 動態jdk代理
	// }
	// public DaoFrameUseTypeInterface
	// getDaoFrameUseTypeInterface(FrameDataSqlDMLUse frameDataSqlDMLUse) {
	// return
	// DaoFrameConntroller.getDaoFrameUseTypeInterface(frameDataSqlDMLUse.getValue().getName());
	// }

}
